package com.chris.datacnter.dao;


import com.chris.datacnter.model.DcRuntimeEo;
import com.core.data.jdbc.BaseDAO;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class DcRuntimeDAO extends BaseDAO {

    /**
     * 根据条件获取正在注册运行的机器
     * @param syncTag
     * @param ns
     * @return
     */
    public List<DcRuntimeEo> getRuntimeData(String syncTag,String ns)
    {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String condition = "sync_tag = '"+syncTag+"' and ns = '"+ns+"'  and code_state=0 and off_time>='" + LocalDateTime.now().format(formatter) +"'";
        List<DcRuntimeEo> list =baseFindAllByCondition(condition,DcRuntimeEo.class);
        return  list;
    }

    /**
     * 根据条件获取正在注册运行的机器ID集合
     * @param ns
     * @return
     */
    public List<DcRuntimeEo>  getRuntimeData(String ns)
    {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String condition = " ns = '"+ns+"' and code_state=0 and off_time>='" + LocalDateTime.now().format(formatter) +"'";
        List<DcRuntimeEo> list =baseFindAllByCondition(condition,DcRuntimeEo.class);
        return  list;
    }

    /**
     * 更新运行心跳时间和过期时间
     * @param id
     * @param sync_max_time(毫秒）
     * @return
     */
    public int updateRuntimeData(int id,long sync_max_time)
    {
        long s_sync_max_time=sync_max_time/1000;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String sql ="update dc_runtime set code_state=0 , last_sync_time='"+  LocalDateTime.now().format(formatter) +"' , off_time ='"+LocalDateTime.now().plusSeconds(s_sync_max_time).format(formatter) +"' , sync_max_time='"+sync_max_time+"' "+
                " where id = "+id;
       return baseUpdate(sql);
    }

    /**
     * 更新检测所有过期数据
     * @return
     */
    public int docheck()
    {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String sql ="update dc_runtime set code_state=1 "+
                " where code_state = 0  and off_time < '"+LocalDateTime.now().format(formatter)+"'";
        return baseUpdate(sql);
    }

}
